package com.mdxx.xczd.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;
import com.google.gson.Gson;
import com.mdxx.xczd.api.ApiManage;
import com.mdxx.xczd.bean.VersionInfo;
import com.mdxx.xczd.bean.VersionInfoResult;
import com.orhanobut.logger.Logger;
import java.io.File;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class VersionUpdateUtil {
	private Context context;
	private ProgressDialog progressDialog;
	public VersionUpdateUtil(Context context){
		this.context = context;
	}

	public boolean isCheckUp(int apkVersion){
		if( apkVersion > getCurrentVersion()){
			return true;
		}	
		return false;
	}

	/**
	 * 获取系统当前的版本
	 */
	public int getCurrentVersion(){		
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}
	/**
 	* 获取系统当前的版本名称
 	*/
	public static String getCurrentVersionName(Context context){
		String versionName = "";
		try {
			versionName = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
			versionName = "V" + versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionName;
	}


	public void checkVersion(final int type) {
		ApiManage.getInstence().getApiService().updateVersion("custom")
				.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<VersionInfoResult>(){
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {
				Logger.json(e.toString());
				ToastUtil.showShort("请求网络失败");
			}

			@Override
			public void onNext(VersionInfoResult versionInfoResult) {
				Logger.json( new Gson().toJson(versionInfoResult));
				if(0 == versionInfoResult.code){
					VersionInfo versionInfo = versionInfoResult.data;
					if(isCheckUp(versionInfo.num)){
						showUpdateDialog(versionInfo.apkDownloadUrl);
					}else{
						if(type == 0){

						}else{
							ToastUtil.showShort("当前已是最新版本");
						}
					}
				}/*else{
					ToastUtil.showShort(versionInfoResult.errorMsg);
				}*/
			}
		});
	}


	public void showUpdateDialog(final String apkDownloadUrl) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("巡查终端");
		builder.setMessage("检测到新版本，立即更新吗?");
		builder.setCancelable(false);
		builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showDownloadDialog(apkDownloadUrl);
			}
		});
		builder.setNegativeButton("稍后更新", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				/*if(isFinish != null){
					isFinish.finish();   //进入主界面
				}*/
			}

		});
		builder.create().show();
	}



	public void showDownloadDialog(String url) {
		String appName = "XCZD.apk";
		String target = Environment.getExternalStorageDirectory()+ File.separator+appName;
		if(isFileExist(target)){
			deleteFile(target);
		}
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
			progressDialog = new ProgressDialog(context);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setTitle("提示信息");
			progressDialog.setIcon(android.R.drawable.stat_sys_download);
			progressDialog.setMessage("正在下载...");
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();

			OkHttpManager.downloadFileAsyn(url, target,new OkHttpManager.ProgressListener(){
						@Override
						public void update(long bytesRead, long contentLength) {
							Logger.d("bytesRead="+bytesRead+"----contentLength"+contentLength);
							int pre = (int)contentLength / 100;
							progressDialog.setMax(100);
							if(bytesRead < contentLength){
								progressDialog.setProgress((int)bytesRead/pre);
							}
						}
					},
					new OkHttpManager.ResultCallback<String>() {
				@Override
				public void onError(Exception e) {
					progressDialog.dismiss();
				}

				@Override
				public void onResponse(String response) {
					progressDialog.dismiss();
					File file = new File(response);
					installNewApk(file);
				}


			});
		}else{
			Toast.makeText(context, "我是toast哦哦哦哦", Toast.LENGTH_SHORT).show();
		}				
	}

	protected void installNewApk(File result) {		
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.setDataAndType(Uri.fromFile(result), "application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	public String getAppName(String url){
		return url.substring(url.lastIndexOf("/")+1);
	}

	public boolean isFileExist(String target){
		File file = new File(target);
		if(file.exists()){
			return true;
		}
		return false;
	}

	public void deleteFile(String  target){
		File file = new File(target);
		file.delete();
	}

	public IsFinish isFinish;

	public void setIsFinish(IsFinish isFinish) {
		this.isFinish = isFinish;
	}

	public interface IsFinish{
		public void finish();
	}
}
